import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTaskStore = defineStore('tasks', () => {
  // 任务列表初始数据
  const tasks = ref([
    { 
      id: 1, 
      title: '设计登录页面', 
      description: '设计用户登录界面UI', 
      priority: 'high', 
      status: 'doing', 
      assignedTo: 1, 
      createdAt: new Date('2023-05-01') 
    },
    { 
      id: 2, 
      title: 'API接口开发', 
      description: '开发用户认证API', 
      priority: 'high', 
      status: 'todo', 
      createdAt: new Date('2023-05-02') 
    },
    { 
      id: 3, 
      title: '数据库设计', 
      description: '设计用户数据表结构', 
      priority: 'medium', 
      status: 'done', 
      assignedTo: 3, 
      createdAt: new Date('2023-05-01'), 
      completedAt: new Date('2023-05-05') 
    }
  ])
  
  // 成员列表初始数据
  const members = ref([
    { id: 1, name: '许婉婷', capacity: 8, currentLoad: 2 },
    { id: 2, name: '郭新华', capacity: 6, currentLoad: 1 },
    { id: 3, name: '梁正林', capacity: 7, currentLoad: 3 },
    { id: 4, name: '周星星', capacity: 5, currentLoad: 0 },
    { id: 5, name: '王建斌', capacity: 8, currentLoad: 4 },
    { id: 6, name: '李华', capacity: 6, currentLoad: 1 },
    { id: 7, name: '王芳', capacity: 5, currentLoad: 0 }
  ])
  
  /**
   * 按状态分类的任务计算属性
   * @returns {Object} 按状态分组的任务对象
   */
  const tasksByStatus = computed(() => {
    return {
      todo: tasks.value.filter(t => t.status === 'todo'),
      doing: tasks.value.filter(t => t.status === 'doing'),
      done: tasks.value.filter(t => t.status === 'done')
    }
  })
  
  /**
   * 成员工作效率计算属性
   * @returns {Array} 包含每个成员效率信息的数组
   */
  const memberEfficiency = computed(() => {
    return members.value.map(member => {
      const completedTasks = tasks.value.filter(
        t => t.assignedTo === member.id && t.status === 'done'
      ).length
      return {
        id: member.id,
        name: member.name,
        efficiency: member.capacity > 0 
          ? Math.round((completedTasks / member.capacity) * 100)
          : 0
      }
    })
  })

  /**
   * 添加新任务
   * @param {Object} task - 新任务对象
   * @throws {Error} 当任务标题为空时抛出错误
   */
  const addTask = (task) => {
    if (!task?.title) {
      throw new Error('任务标题不能为空')
    }
    
    tasks.value.push({
      id: Date.now(),
      ...task,
      status: 'todo',
      createdAt: new Date()
    })
  }
  
  /**
   * 更新任务状态
   * @param {number} taskId - 任务ID
   * @param {string} newStatus - 新状态 ('todo'|'doing'|'done')
   * @returns {boolean} 是否更新成功
   */
  const updateTaskStatus = (taskId, newStatus) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return false

    // 状态变更逻辑
    if (task.status === 'doing' && newStatus === 'done') {
      const member = members.value.find(m => m.id === task.assignedTo)
      if (member) member.currentLoad = Math.max(0, member.currentLoad - 1)
      task.completedAt = new Date()
    }
    else if (task.status === 'todo' && newStatus === 'doing' && task.assignedTo) {
      const member = members.value.find(m => m.id === task.assignedTo)
      if (member) member.currentLoad += 1
    }

    task.status = newStatus
    return true
  }

  /**
   * 删除任务
   * @param {number} taskId - 要删除的任务ID
   * @returns {boolean} 是否删除成功
   */
  const deleteTask = (taskId) => {
    const taskIndex = tasks.value.findIndex(t => t.id === taskId)
    if (taskIndex === -1) return false

    const task = tasks.value[taskIndex]
    if (task.assignedTo && task.status === 'doing') {
      const member = members.value.find(m => m.id === task.assignedTo)
      if (member) member.currentLoad = Math.max(0, member.currentLoad - 1)
    }

    tasks.value.splice(taskIndex, 1)
    return true
  }

  /**
   * 智能分配任务
   * @param {number} taskId - 要分配的任务ID
   * @returns {boolean} 是否分配成功
   */
  const autoAssignTask = (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task || task.assignedTo) return false

    const availableMember = [...members.value]
      .sort((a, b) => a.currentLoad - b.currentLoad)[0]

    if (availableMember?.currentLoad < availableMember.capacity) {
      task.assignedTo = availableMember.id
      availableMember.currentLoad += 1
      return true
    }
    return false
  }

  /**
   * 更新成员工作容量
   * @param {number} memberId - 成员ID
   * @param {number} newCapacity - 新容量值
   * @returns {boolean} 是否更新成功
   */
  const updateMemberCapacity = (memberId, newCapacity) => {
    if (newCapacity < 0) return false
    
    const member = members.value.find(m => m.id === memberId)
    if (!member) return false
    
    member.capacity = newCapacity
    return true
  }

  return {
    tasks,
    members,
    tasksByStatus,
    memberEfficiency,
    addTask,
    updateTaskStatus,
    deleteTask,
    autoAssignTask,
    updateMemberCapacity
  }
})